package init

import (
	"fmt"
	"ginchat/internal/globals"
	"ginchat/utils/message"
	"sync"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

func Init() *sync.WaitGroup {
	wg := MessageInit()
	err := ViperInit()
	if err != nil {
		message.PrintErr(err)
		message.Exit()
	}

	return wg
}

func MessageInit() *sync.WaitGroup {
	wg := globals.GetWaitGroup()
	wg.Add(1)
	go message.InitMessage()
	return wg
}

func ViperInit() error {
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./configs")
	viper.SetConfigName("config")

	err := viper.ReadInConfig()
	if err != nil {
		return err
	}

	viper.WatchConfig()

	viper.OnConfigChange(func(in fsnotify.Event) {
		args := fmt.Sprintf("Config File: %s has been changed, ops is %s.\n", in.Name, in.Op)
		message.Println(args)
	})

	return nil
}
